#! /usr/bin/env python
# -*- coding: utf-8 -*-
#  Vasily Yevstygnyeyev 2010 (c)  <bazilxp@gmail.com>
#  Python Email Shell


import email
import poplib
import os
import base64
import commands

bheader='Content-Transfer-Encoding: base64'
master_email='master@mail.com' #мыло хозяина

src_mail='mymail@mail.com' # мыло которое проверяем
pop_user='user'
pop_pass='pass'
pop_host='pop.server.com'
smtp_host='smtp.server.com'
gpg_email='mail@mail.com' # это используется для gpg мыло

pop_port=110
pop_timeout=60
unix_user='unixuser' # пользователь в системе

# каталоги желательно создать
mail_folder=    '/home/'+unix_user+'/email-shell/msg/'   
gpg_folder=     '/home/'+unix_user+'/email-shell/gpg/'
incoming_folder='/home/'+unix_user+'/email-shell/cmd/'
log_file=       '/home/'+unix_user+'/email-shell/log/result.log'

def CheckMail():
     M=poplib.POP3(pop_host,pop_port,pop_timeout)
     M.user(pop_user)
     M.pass_(pop_pass)
     print M.stat()
     numMessages = len(M.list()[1])
     for i in range(numMessages):
          f1=open(mail_folder+str(i)+'.txt','w')
          print 'create '+str(i)+'.txt'

          for j in M.retr(i+1)[1]:
               f1.write(j)
               f1.write('\n')         
          f1.close
          M.dele(i+1) 
     M.quit()

def ParseMail():
   m=os.listdir(mail_folder)

   for n in m:
      f1=open(mail_folder+n)
      s=f1.read()
      f1.close()

      msg = email.message_from_string(s)
      if msg['From'].find(master_email)>-1:   
         print 'Master email '+n
         for x in  msg.get_payload():
            at=str(x)
            pos=at.find(bheader)
         if pos > -1 :
            pos+=len(bheader)
            f1=open(gpg_folder+'at.gpg','w')
            f1.write(base64.b64decode(at[pos:]))
            f1.close()            
            commands.getoutput('gpg -d '+gpg_folder+'at.gpg > '+incoming_folder+'1.sh ; chmod +x '+incoming_folder+'1.sh' )
            os.remove(gpg_folder+'at.gpg')
      os.remove(mail_folder+n)

def RunScript():
    scripts=os.listdir(incoming_folder)
    outcmd=''
    for x in scripts:
        outcmd=outcmd+'\n------------------- '+x+'--------------------\n'
        outcmd=outcmd+commands.getoutput(incoming_folder+x)
        outcmd=outcmd+'\n------------------- '+x+'--------------------\n'
        os.remove(incoming_folder+x) # kill script
    if len(scripts)>0 :
       print 'writing log '+log_file
       f1=open(log_file,'w')
       f1.write(outcmd)
       f1.close()
       #clean up
       if os.path.exists(log_file+'.gpg') : os.remove(log_file+'.gpg')
       print 'encrypt '+log_file
       commands.getoutput('gpg -e -r '+gpg_email+' '+log_file)
       print 'remove '+log_file
       os.remove(log_file)

def DropMail():
   subj='"Cron Job executed"'
   msg='"Hello!  I was proud  to inform that your  task is completed"'
   drop_mail='sendEmail -f '+src_mail+' -t '+master_email+' -xu '+pop_user+' -xp '+pop_pass+'-a '+log_file+'.gpg  -s  '+smtp_host+' -u '+subj+' -m '+msg
   commands.getoutput(drop_mail)

if os.path.exists(incoming_folder+'1.sh'): exit(1)
CheckMail()
ParseMail()
RunScript()
if os.path.exists(log_file+'.gpg'): 
   DropMail()
   os.remove(log_file+'.gpg')
